<template>
  <PageWrapper title="修改当前用户密码" content="修改成功后会自动退出当前登录！">
    <div class="py-8 bg-white flex flex-col justify-center items-center">
      <BasicForm @register="register" />
      <div class="flex justify-center">
        <a-button @click="resetFields"> 重置 </a-button>
        <a-button class="!ml-4" type="primary" @click="handleSubmit"> 确认 </a-button>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
import { PageWrapper } from '@/components/Page';
import { BasicForm, useForm } from '@/components/Form';
import JSEncrypt from 'jsencrypt';
import { formSchema } from './pwd.data';
import { changePassword } from '@/api/sys/user';
import { useRequest } from '@vben/hooks'
import { getPublicKey } from '@/api/sys/login'
import { useUserStore } from '@/store/modules/user';
import { useMessage } from '@/hooks/web/useMessage';

defineOptions({ name: 'ChangePassword' });
const userStore = useUserStore()
const { createMessage } = useMessage()
const { data: encryptKey } = useRequest(getPublicKey)
const [register, { validate, resetFields }] = useForm({
  size: 'large',
  baseColProps: { span: 24 },
  labelWidth: 100,
  showActionButtonGroup: false,
  schemas: formSchema,
});

const rsaEncryptData = (text: string, key: string) => {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey(key)
  return encrypt.encrypt(text) as string
}

async function handleSubmit() {
  try {
    const values = await validate();
    const { passwordOld, passwordNew } = values;
    // console.log(passwordOld, passwordNew);
    const ret = await changePassword({
      oldPassword: rsaEncryptData(passwordOld, encryptKey.value),
      newPassword: rsaEncryptData(passwordNew, encryptKey.value),
    })
    ret && createMessage.success(ret)
    userStore.confirmLoginOut()
    // const { router } = useRouter();
    // router.push(pageEnum.BASE_LOGIN);
  } catch (error) {
    console.error(error);
  }
};

</script>
